package com.unionftech.common.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.annotation.ColorRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.app.SkinAppCompatDelegateImpl
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.FragmentActivity
import com.unionftech.common.CommonConstants
import com.unionftech.common.R
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.utils.ActivityCollector
import com.unionftech.common.utils.SpUtils
import com.unionftech.common.utils.StatusBarUtil
import com.unionftech.common.utils.ToastUtils
import com.unionftech.common.utils.Utils
import com.unionftech.common.widget.LoadingDialog
import com.unionftech.common.widget.RootView
import skin.support.content.res.SkinCompatResources
import java.lang.ref.WeakReference

abstract class BaseActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var weakReference: WeakReference<Activity>
    private var lastClick: Long = 0L
    protected lateinit var mContext: Context
    protected lateinit var mActivity: FragmentActivity
    protected lateinit var mRootView: RootView
    private lateinit var mLoadingDialog: LoadingDialog
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getIntentData()
        if (!::weakReference.isInitialized) {
            weakReference = WeakReference(this)
        }
        weakReference.get()?.let {
            ActivityCollector.addActivity(it)
        }
        mContext = WeakReference(this).get()!!
        mActivity = WeakReference(this).get()!!
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        initData()
        initRootView()
        if (isImmersionBar()) {
            statusBar()
        }
        initView()
        //设置主题
        initLanguageText()
        setListener()
        setView()

    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        getIntentData()
    }

    private fun initRootView() {
        mRootView = RootView(mContext)
        showBackImg()
        setCustomerServer()
        if (initLayout() != 0) {
            mRootView.addContentView(initLayout())
        }
        super.setContentView(mRootView)
    }

    /**
     * 设置客服图标
     */
    private fun setCustomerServer() {
        setRightImg(R.drawable.ic_headphones) {
            ToastUtils.longToast(
                DynamicResourceManager.getString(R.string.developing)
            )
        }
    }


    /**
     * 初始化布局
     */
    protected abstract fun initLayout(): Int

    private fun getIntentData() {
        intent?.let {
            obtainIntentData(it)
        }
    }

    protected open fun obtainIntentData(intent: Intent) {

    }

    /**
     *初始化View
     */
    protected open fun initView() {

    }

    /**
     * 初始化界面语言Text,
     * 需要将整个界面需要展示的组件文字全部重新setText一遍
     */
    protected open fun initLanguageText() {

    }

    /**
     * 设置监听
     */
    protected open fun setListener() {

    }

    /**
     * 设置View
     */
    protected open fun setView() {

    }

    /**
     * 初始化数据
     */
    protected open fun initData() {

    }

    /**
     * 加载数据
     */
    protected open fun loadData() {

    }

    protected fun getRootView(): RootView {
        return mRootView
    }

    fun immersive(@ColorRes color: Int, rootView: RootView) {
        StatusBarUtil.darkMode(this, true)
        StatusBarUtil.setNavbarColor(this, resources.getColor(color))
        StatusBarUtil.immersive(this, resources.getColor(color))
        StatusBarUtil.setPaddingSmart(this, rootView)
    }

    fun immersiveSkin(@ColorRes color: Int) {
        val isFollowSystem =
            SpUtils.getInstance().getBoolean(CommonConstants.Key.KEY_FOLLOW_SYSTEM, false)
        var isDark = SpUtils.getInstance().getBoolean(CommonConstants.Key.KEY_IS_DARK_MODE, false)
        if (isFollowSystem) {
            isDark = Utils.isDarkModeEnable(mContext)
        }
        StatusBarUtil.darkMode(this, !isDark)
        StatusBarUtil.setNavbarColor(
            this, SkinCompatResources.getColor(mContext, color)
        )
        StatusBarUtil.immersive(
            this, SkinCompatResources.getColor(mContext, color)
        )
    }

    fun showBackImg() {
        mRootView.showTitleBar()
        mRootView.showBackImg(this)
    }

    fun showBackImg(resId: Int) {
        mRootView.showTitleBar()
        mRootView.showBackImg(resId)
        mRootView.showBackImg(this)
    }

    fun setActivityTitle(title: String) {
        mRootView.showTitle(title)
    }

    fun hideCenterTitle() {
        mRootView.hideTitleText()
    }

    fun setActivityTitle(resId: Int) {
        mRootView.showTitle(resId)
    }

    fun hideTitleBar() {
        mRootView.hideTitleBar()
    }

    fun hideBackImg() {
        mRootView.hideBackImg()
    }

    fun setRightImg(resId: Int, listener: OnClickListener) {
        mRootView.showRightImg(resId, listener)
    }

    fun setBackText(text: String) {
        mRootView.showBackText()
        mRootView.setBackText(text)
    }

    fun setBackText(text: String, color: Int) {
        mRootView.showBackText()
        mRootView.setBackText(text)
        mRootView.setBackTextColor(color)
    }

    fun setRightText(text: String) {
        mRootView.showRightText(text)
    }

    fun setRightText(text: String, listener: OnClickListener) {
        mRootView.showRightText(text, listener)
    }

    fun setRightText(resId: Int) {
        mRootView.showRightText(resId)
    }

    fun setRightText(resId: Int, listener: OnClickListener) {
        mRootView.showRightText(resId, listener)
    }

    fun hideRightText() {
        mRootView.hideRightText()
    }

    fun setRightTextColor(color: Int) {
        mRootView.setRightTextColor(color)
    }

    fun showTitleDivider() {
        mRootView.showTitleDivider()
    }

    /**
     * View点击
     */
    protected open fun doClick(v: View?) {
        if (v?.id == R.id.iv_back) {
            back()
        }
    }

    private fun back() {
        if (!backPressed()) {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    /**
     * 标题栏的返回按钮的默认操作，可以重写此方法，更改操作
     */
    protected open fun backPressed(): Boolean {
        return false
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
        currentFocus?.run {
            hideSoftInput()
        }
    }

    protected open fun isImmersionBar(): Boolean {
        return true
    }

    protected open fun statusBar() {
        immersive(R.color.color_white, mRootView)
    }

    open fun showLoading() {
        currentFocus?.run {
            hideSoftInput()
        }
        if (!::mLoadingDialog.isInitialized) {
            mLoadingDialog = LoadingDialog(this)
        }
        mLoadingDialog.show()
    }

    open fun hideLoading() {
        if (::mLoadingDialog.isInitialized && mLoadingDialog.isShowing) {
            mLoadingDialog.dismiss()
        }
    }

    /**
     * 全屏显示
     */
    protected fun fullScreen() {
        StatusBarUtil.fullScreen(this, true)
    }


    /**
     * 退出全屏
     */
    protected fun quitFullScreen() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            WindowCompat.setDecorFitsSystemWindows(window, true)
            WindowCompat.getInsetsController(window, window.decorView)?.let { controller ->
                controller.show(WindowInsetsCompat.Type.systemBars())
            }
        } else {
            window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        }
    }

    /**
     * 防止用户快速点击
     */
    private fun fastClick(): Boolean {
        if (System.currentTimeMillis() - lastClick <= 1000) {
            return false
        }
        lastClick = System.currentTimeMillis()
        return true
    }

    override fun onClick(v: View?) {
        if (fastClick()) {
            doClick(v)
        }
    }

    /**
     * 隐藏软件盘
     */
    fun hideSoftInput() {
        val manager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        currentFocus?.run {
            manager.hideSoftInputFromWindow(this.windowToken, 0)
        }
    }

    /**
     * 显示软件盘
     */
    fun showSoftInput() {
        val manager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        window?.decorView?.run {
            manager.showSoftInput(this, 0)
        }
    }

    override fun getDelegate(): AppCompatDelegate {
        return SkinAppCompatDelegateImpl.get(this, this);
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this)
    }

    open fun getContext(): Context {
        return mContext
    }

}